﻿using LdtDataEngin.ModuleDetail.BaseModule.Optimization;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.CommHelp;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.DataModel.SystemtableModel;
using LdtJudge.DataEngine.Model.EvidenceFact;
using LdtJudge.DataEngine.Model.EvidenceQuestion;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;

namespace LdtDataEngin.ModuleDetail.OptimizationModule.EvidenceDerivation
{
    public class FactEvidenc : OptimizationBase
    {
        public EvidenctFactModel evidenctFactModel { get; set; }
        /// <summary>
        /// 声明配置类
        /// </summary>
        /// <param name="xmlconfig"></param>
        public FactEvidenc(DataContext dataContext, EvidenctFactModel xmlconfig)
        {
            this.dataContext = dataContext;
            evidenctFactModel = xmlconfig;
        }

        /// <summary>
        /// 执行证据与事实要素对比
        /// </summary>
        public void Extract()
        {
            List<List<FileName>> evidenceList = EvidenceExtract();
            List<List<FileName>> factList = FactExtract();

            if (evidenceList.Count > 0 && factList.Count > 0)
            {
                evidenceList = evidenceList.Where(a => a.FirstOrDefault(b => b.name == evidenctFactModel.ResultModel.evidenctype && b.fileValue == "t2") != null).ToList();
                factList = factList.Where(a => a.FirstOrDefault(b => b.name == evidenctFactModel.ResultModel.facttype && b.fileValue == "2") != null).ToList();
                foreach (List<FileName> evidenctValueList in evidenceList)
                {
                    string suitdegreeid = GetListValue(evidenctValueList, evidenctFactModel.ResultModel.suitdegreeid);
                    string name = GetListValue(evidenctValueList, evidenctFactModel.ResultModel.name);
                    List<SYS_ArgumentType> dataTableArgumentType = DictionariesConver.GetTabl_SysArgumentTypeTable(GetListValue(evidenctValueList, evidenctFactModel.ResultModel.evidenctype));
                    bool flag = true;

                    //被害人
                    if (suitdegreeid == "t2")
                    {
                        string regTextAppend = "";
                        List<List<FileName>> fileNameList = evidenceList.Where(a => a.FirstOrDefault(b => b.name == evidenctFactModel.ResultModel.suitdegreeid && b.fileValue == "t2") != null).ToList();
                        if (fileNameList.Count > 1)
                        {
                            //参与人身份和名字组合  如 被害人xxx
                            regTextAppend = DictionariesConver.GetArgumentName("paramter", "PartakeSuitDegree", "t2") + name;
                        }
                        else
                        {
                            regTextAppend = name;
                        }
                        foreach (List<FileName> findrow in factList)
                        {
                            string originaltext = findrow.FirstOrDefault(a => a.name == evidenctFactModel.ResultModel.originaltext).fileValue;
                            if (Regex.IsMatch(originaltext, regTextAppend) || Regex.IsMatch(originaltext, name))
                            {
                                AddNode(evidenctValueList, findrow);
                                flag = false;
                            }
                        }
                    }
                    //被告人
                    if (suitdegreeid == "t1")
                    {
                        string regTextAppend = "";
                        List<List<FileName>> fileNameList = evidenceList.Where(a => a.FirstOrDefault(b => b.name == evidenctFactModel.ResultModel.suitdegreeid && b.fileValue == "t1") != null).ToList();
                        if (fileNameList.Count > 1)
                        {
                            //参与人身份和名字组合  如 被害人xxx
                            regTextAppend = DictionariesConver.GetArgumentName("paramter", "PartakeSuitDegree", "t1") + name;
                        }
                        else
                        {
                            regTextAppend = name;
                        }
                        foreach (List<FileName> findrow in factList)
                        {
                            string originaltext = findrow.FirstOrDefault(a => a.name == evidenctFactModel.ResultModel.originaltext).fileValue;
                            if (Regex.IsMatch(originaltext, regTextAppend) || Regex.IsMatch(originaltext, name))
                            {
                                AddNode(evidenctValueList, findrow);
                                flag = false;
                            }
                        }
                    }
                    //证人
                    if (suitdegreeid == "t3")
                    {
                        string regTextAppend = "";
                        List<List<FileName>> fileNameList = evidenceList.Where(a => a.FirstOrDefault(b => b.name == evidenctFactModel.ResultModel.suitdegreeid && b.fileValue == "t3") != null).ToList();
                        if (fileNameList.Count > 1)
                        {
                            //参与人身份和名字组合  如 被害人xxx
                            regTextAppend = DictionariesConver.GetArgumentName("paramter", "PartakeSuitDegree", "t3") + name;
                        }
                        else
                        {
                            regTextAppend = name;
                        }
                        foreach (List<FileName> findrow in factList)
                        {
                            string originaltext = findrow.FirstOrDefault(a => a.name == evidenctFactModel.ResultModel.originaltext).fileValue;
                            if (Regex.IsMatch(originaltext, regTextAppend) || Regex.IsMatch(originaltext, name))
                            {
                                AddNode(evidenctValueList, findrow);
                                flag = false;
                            }
                        }
                    }
                    //上述都没有匹配成功
                    if (flag)
                    {
                        string fictitiousText = "";
                        if (name.Length == 3)
                        {
                            fictitiousText = DictionariesConver.GetArgumentName("paramter", "PartakeSuitDegree", "t3") + name.Substring(0, 1) + "某某";
                        }
                        else if (name.Length == 2)
                        {
                            fictitiousText = DictionariesConver.GetArgumentName("paramter", "PartakeSuitDegree", "t3") + name.Substring(0, 1) + "某";
                        }
                        if (!string.IsNullOrEmpty(fictitiousText))
                        {
                            foreach (var findrow in factList)
                            {
                                string originaltext = findrow.FirstOrDefault(a => a.name == evidenctFactModel.ResultModel.originaltext).fileValue;
                                if (Regex.IsMatch(originaltext, fictitiousText) || Regex.IsMatch(originaltext, fictitiousText))
                                {
                                    AddNode(evidenctValueList, findrow);
                                    flag = false;
                                }
                            }
                        }

                        //证据名称匹配失败
                        if (flag)
                        {
                            if (dataTableArgumentType.Count > 0)
                            {
                                //关键字匹配
                                string matchKeyWord = dataTableArgumentType[0].AT_MatchKeyWord;
                                string messageWord = Regex.Match(matchKeyWord, @"(?<=" + GetListValue(evidenctValueList, evidenctFactModel.ResultModel.evidenctype) + @"=)[^\r]*?(?=[;]([ta]\d|255))").Value;
                                List<string> matchList = matchKeyWord.Split(';').ToList();
                                List<string> keywordList = messageWord.Split(',').ToList();
                                foreach (string word in keywordList)
                                {
                                    if (Regex.IsMatch(GetListValue(evidenctValueList, evidenctFactModel.ResultModel.evidenctname), word))
                                    {
                                        foreach (var findrow in factList)
                                        {
                                            string originaltext = findrow.FirstOrDefault(a => a.name == evidenctFactModel.ResultModel.originaltext).fileValue;
                                            if (Regex.IsMatch(originaltext, word))
                                            {
                                                AddNode(evidenctValueList, findrow);
                                                flag = false;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = this.dataContext };
            dataContext.DataLayerOpt.OptimizationXml = xmlUtilCommon.DataModelByXml(dataContext.DataLayerOpt.SourdatModleList, "");
        }

        public void AddNode(List<FileName> evidenceList, List<FileName> quesetionList)
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = this.dataContext };
            string id = xmlUtilCommon.CaseNodeUpdate(dataContext.DataLayerOpt.SourdatModleList, evidenctFactModel.ResultModel.ResultXmlpath);
            DataModel dataModelRoot = dataContext.DataLayerOpt.SourdatModleList.FirstOrDefault(a => a.ID == id);

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.AppendChild(xmlDocument.CreateElement("详情"));
            XmlElement xmlNode = (XmlElement)xmlDocument.SelectSingleNode("详情");
            xmlNode.SetAttribute("证据名称ID", GetListValue(evidenceList, evidenctFactModel.ResultModel.evidenctID));
            xmlNode.SetAttribute("事实要素ID", GetListValue(quesetionList, evidenctFactModel.ResultModel.fackID));

            DataSoursModel dataSoursModel = xmlUtilCommon.GetXMLByDataModelBackFill(xmlDocument);
            dataSoursModel.dataModelList.FirstOrDefault(a => a.ParentId == "").ParentId = id;
            dataContext.DataLayerOpt.SourdatModleList.AddRange(dataSoursModel.dataModelList);
        }

        /// <summary>
        /// 更新分析数据
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="attName"></param>
        /// <param name="attValue"></param>
        public void UpdateDataModel(string nodeId, string attName, string attValue)
        {
            attName = attName.Replace("@", "");
            DataModel dataModel = dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList.FirstOrDefault(a => a.ID == nodeId);
            if (dataModel == null)
            {
                var attmodel = dataModel.AttributesList.FirstOrDefault(a => a.Name == attName);
                if (attmodel != null)
                {
                    attmodel.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue = attValue;
                }
                else
                {
                    AttributeInfo attribute = new AttributeInfo();
                    attribute.Name = attName;
                    attribute.sourceList = new List<Source>();
                    Source source = new Source();
                    source.AnalysisStatus = "0";
                    source.SourceCode = dataContext.DataLayerAns.SourceCode;
                    source.IsCheck = "1";
                    source.SaveValue = attValue;
                    attribute.sourceList.Add(source);
                    dataModel.AttributesList.Add(attribute);
                }
            }

        }

        /// <summary>
        /// 获取证据对象
        /// </summary>
        /// <returns></returns>
        public List<List<FileName>> EvidenceExtract()
        {
            List<List<FileName>> fileNamesList = new List<List<FileName>>();
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = this.dataContext };
            LdtJudge.DataEngine.Model.EvidenceQuestion.EvidenceModel evidenceModel = evidenctFactModel.EvidenceModel;
            Dictionary<string, List<FileName>> evidenceDic = new Dictionary<string, List<FileName>>();
            // 去掉阶段属性的过滤，证据的内容在datamodellist中存储的没有阶段
            List<string> pathArr = evidenceModel.path.Split('/')?.ToList();
            int detailIndex = pathArr.FindIndex(a=>a.StartsWith("详情[@阶段="));
            pathArr[detailIndex] = "详情";
            string eviPath = string.Join("/", pathArr);
            if (dataContext.DataLayerOpt.SourdatModleList.FirstOrDefault(a => a.XmlPath == eviPath) != null)
            {
                List<DataModel> dataModelList = dataContext.DataLayerOpt.SourdatModleList.Where(a => a.XmlPath == eviPath).ToList();
                foreach (DataModel dataModelRoot in dataModelList)
                {
                    List<FileName> fileNameList = new List<FileName>();

                    List<DataModel> suberList = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, dataModelRoot);
                    foreach (LdtJudge.DataEngine.Model.EvidenceQuestion.EvidenceModel evidenceNode in evidenceModel.evidenceModelList)
                    {
                        if (suberList.FirstOrDefault(a => a.XmlPath == dataModelRoot.XmlPath + evidenceNode.path) != null)
                        {
                            List<DataModel> dataModeNodelList = suberList.Where(a => a.XmlPath == dataModelRoot.XmlPath + evidenceNode.path).ToList();
                            foreach (DataModel dataModelNode in dataModeNodelList)
                            {
                                foreach (FileName frileitem in evidenceNode.fileNameList)
                                {
                                    frileitem.fileValue = GetAttValue(dataModelNode, frileitem.value);
                                    frileitem.NodeID = dataModelNode.ID;
                                    frileitem.ParentID = dataModelRoot.ID;
                                    frileitem.xPath = dataModelRoot.XmlPath + evidenceNode.path;
                                    FileName fileNames = JsonConvert.DeserializeObject<FileName>(JsonConvert.SerializeObject(frileitem));
                                    fileNameList.Add(fileNames);
                                }
                            }
                        }
                    }
                    fileNamesList.Add(fileNameList);

                }
            }
            return fileNamesList;
        }

        /// <summary>
        /// 获取质证对象
        /// </summary>
        public List<List<FileName>> FactExtract()
        {
            List<List<FileName>> fileNamesList = new List<List<FileName>>();
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = this.dataContext };
            FactModel questionModel = evidenctFactModel.factModel;
            // 去掉阶段属性的过滤，证据的内容在datamodellist中存储的没有阶段
            List<string> pathArr = questionModel.path.Split('/')?.ToList();
            int detailIndex = pathArr.FindIndex(a => a.StartsWith("详情[@阶段="));
            pathArr[detailIndex] = "详情";
            string factPath = string.Join("/", pathArr);
            if (dataContext.DataLayerOpt.SourdatModleList.FirstOrDefault(a => a.XmlPath == factPath) != null)
            {
                List<DataModel> dataModelList = dataContext.DataLayerOpt.SourdatModleList.Where(a => a.XmlPath == factPath).ToList();
                foreach (DataModel dataModelRoot in dataModelList)
                {
                    List<FileName> fileNameList = new List<FileName>();
                    List<DataModel> suberList = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, dataModelRoot);
                    foreach (QuestionModel questionNode in questionModel.questionModelList)
                    {
                        if (suberList.FirstOrDefault(a => a.XmlPath == dataModelRoot.XmlPath + questionNode.path) != null)
                        {
                            List<DataModel> dataModeNodelList = suberList.Where(a => a.XmlPath == dataModelRoot.XmlPath + questionNode.path).ToList();
                            foreach (DataModel dataModelNode in dataModeNodelList)
                            {
                                foreach (FileName frileitem in questionNode.fileNameList)
                                {
                                    frileitem.fileValue = GetAttValue(dataModelNode, frileitem.value);
                                    frileitem.NodeID = dataModelNode.ID;
                                    frileitem.xPath = dataModelRoot.XmlPath + questionNode.path;
                                    frileitem.ParentID = dataModelRoot.ID;
                                    FileName fileNames = JsonConvert.DeserializeObject<FileName>(JsonConvert.SerializeObject(frileitem));
                                    fileNameList.Add(fileNames);
                                }
                            }
                        }
                    }
                    fileNamesList.Add(fileNameList);
                }
            }
            return fileNamesList;
        }

        /// <summary>
        /// 获取属性值
        /// </summary>
        /// <param name="dataModel">节点内容</param>
        /// <param name="dataModel">节点内容</param>
        /// <returns></returns>
        public string GetAttValue(DataModel dataModel, string attName)
        {
            attName = attName.Replace("@", "");
            string value = "";
            if (dataModel.AttributesList.FirstOrDefault(a => a.Name == attName) != null)
            {
                value = dataModel.AttributesList.FirstOrDefault(a => a.Name == attName).sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;

            }
            if (attName.ToLower() == "id")
            {
                value = dataModel.ID;
            }
            return value;
        }

        /// <summary>
        /// 获取集合中字段的值
        /// </summary>
        /// <param name="fileNameList">数据集合</param>
        /// <param name="name">标识</param>
        /// <returns></returns>
        public string GetListValue(List<FileName> fileNameList, string name)
        {
            string value = "";
            if (fileNameList.FirstOrDefault(a => a.name == name) != null)
            {
                FileName fileName = fileNameList.FirstOrDefault(a => a.name == name);
                value = fileName.fileValue;
            }
            return value;
        }
    }
}
